/********************
点击考核名称后的指标填报弹窗
** */
<template>
  <el-dialog
    width="80%"
    title="指标填报"
    :close-on-click-modal="false"
    :visible.sync="visible"
    top="8vh"
    @close="closeDialog()"
  >
    <el-form ref="dataForm" :model="dataForm" label-position="right" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="考核名称:" prop="name" style="width:60%">
            <span>{{dataForm.name}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="周期名称:" prop="date" style="width:60%">
            <span>{{dataForm.period}}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="考核时间:" prop="sname" style="width:60%">
            <span>{{dataForm.assessBeginTime?dataForm.assessBeginTime.slice(0,10):""}}--{{dataForm.assessEndTime?dataForm.assessEndTime.slice(0,10):''}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="dataForm.type==0?'被考核人':'被考核机构'" prop="ids" style="width:60%;">
            <span v-if="dataForm.type==0">
              <span v-for="it in dataForm.assessTarget" :key="it">{{it}},</span>
            </span>
            <span v-else>
              <span v-for="it in dataForm.assessTarget1" :key="it">{{it}},</span>
            </span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="height: 10px; border-top: 1px solid #b0bde2"></div>
    <div class="tabBox">
      <div class="btnBox">
        <div>
          <el-button icon="el-icon-plus" type="success" circle @click="showTarLibrary"></el-button>
          <el-button
            @click="deleteIndexRow"
            type="danger"
            icon="el-icon-delete"
            circle
            :disabled="isDelete"
          ></el-button>
        </div>
      </div>
    </div>
    <el-row>
      <el-table
        style="width: 100%;margin-top:20px"
        :data="dataList"
        border
        stripe
        header-align="center"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="type" align="center" label="指标类别" width="140"></el-table-column>
        <el-table-column prop="name" align="center" label="指标名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="weight" align="center" label="权重">
          <template slot-scope="scope">
<!--            <el-form :model="scope.row" :rules="rules">
              <el-form-item prop="weight">
                <el-input v-model.number="scope.row.weight"></el-input>
              </el-form-item>
            </el-form>-->

            <el-input
              v-model="scope.row.weight"
              oninput="value=value.replace(/[^\d.]/g, '').replace(/^\./g, '').replace(/\.{2,}/g, '.').replace(/(\.\d+)\./g, '$1').replace(/^0+(\d)/, '$1').replace(/(\d{15})\d*/, '$1').replace(/(\.\d{2})\d*/, '$1')"
              placeholder="权重"
            ></el-input>

          </template>
        </el-table-column>

        <el-table-column prop="formula" align="center" label="计算公式" show-overflow-tooltip></el-table-column>
        <el-table-column prop="targetValue" align="center" label="目标值" min-width="120">
          <template slot-scope="scope">
            <span>
              <el-input v-model="scope.row.targetValue"
                        :rows="1"
                        type="textarea"></el-input>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="unit" align="center" label="单位" show-overflow-tooltip></el-table-column>
        <el-table-column prop="completeValue" align="center" label="完成值获取方式" width="150">
          <template slot-scope="scope">
            <el-select
              @change="$set(scope.row, scope.row.completeValue, $event)"
              :clearable="true"
              v-model="scope.row.completeValue"
              placeholder="请选择"
            >
              <el-option
                v-for="item in dataFromList"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="provideDeptName" align="center" label="数据提供部门" show-overflow-tooltip>
          <template slot-scope="scope">
            <span
              v-if="scope.row.editFlag == 1"
              style="color:blue"
              @click="showDataProvide(scope.row,scope.$index)"
            >
              <span
                style="color:blue"
                v-if="scope.row.isLiaison == 0"
              >
                 {{scope.row.provideRealName}}
                 <i class="el-icon-edit-outline"></i>
              </span>
                <span
                  v-else
                  style="color:blue"
                  @click="showDataProvide(scope.row,scope.$index)"
                >
                {{scope.row.provideDeptName}}
                <i class="el-icon-edit-outline"></i>
              </span>

            </span>
            <span v-else >
              {{scope.row.provideDeptName}}
            </span>
          </template>
        </el-table-column>
        <!--<el-table-column prop="itemIndex" align="center" label="排序号" show-overflow-tooltip></el-table-column>-->
      </el-table>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" plain @click="handleConfirm">确定</el-button>
      <el-button type="primary" plain @click="closeDialog()">返回</el-button>
    </span>
    <FormulateDialog v-if="formulateDialog" ref="formulateDialog" @submitfy="submitfy1"></FormulateDialog>
    <!-- 日常考核指标库 -->
    <el-dialog title="业绩合同指标库" :visible.sync="dialogVisible" width="80%" append-to-body>
      <zhibiaoTable ref="zhibiaoRef" @func="getRow"></zhibiaoTable>
      <span slot="footer" class="dialog-footer">
        <el-button plain type="primary" @click="addZhibiao">添 加</el-button>
        <el-button plain @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import zhibiaoTable from "@/views/dailyExamine/components/targetIndexTable"; //指标表格
import FormulateDialog from "./formulateDialog"; //数据提供部门选择组件
import {
  targetDetail,
  targetNeedFill,
  saveFillTarget,
  checkitem,
  indexExaminAllDataList
} from "@/api/dailyExamine/targetExamine/indicatorFormulation";
import { getObj } from "@/api/admin/user.js";
import { remote as remoteDict } from "@/api/admin/dict"; //数据获取方式接口
import { validatenull } from "@/util/validate"; //判断空

export default {
  data() {
    return {
      fatherData: {},
      chooseTarget: [], //指标数组
      isDelete: true, //是否能删除
      dialogVisible: false, //指标库显隐
      multipleSelection: [], //选择数组
      dataList: [], //表格数据
      oldDataList:[],//原始表格数据
      visible: false, //最外层弹窗
      dataForm: {}, //表单对象
      userData: {}, //登录人信息对象
      dataFromList:[],//数据获取方式列表
      formulateDialog: false, //数据提供部门/人组件显隐
      isbr:Number,
     /* rules:{
          weight: [
              { required: true,message: "请输入数字", trigger: "blur" },
              {type:"number",message:"权重必须为数字值"}],
      },*/
    };
  },
  watch: {
    // 监听选中
    multipleSelection: {
      handler(val) {
        if (val.length > 0) {
          this.isDelete = false;
        } else {
          this.isDelete = true;
        }
      }
    }
  },
  components: {
    zhibiaoTable, //指标组件
    FormulateDialog
  },
  created() {
    this.getUserData();
  },
  methods: {
    // 获取登录人信息
    getUserData() {
      let id = JSON.parse(sessionStorage.getItem("bfcloud-userInfo")).content
        .userId;
      getObj(id).then(r => {
        this.userData = r.data.data;
      });
    },
    // 删除指标
    deleteIndexRow() {
      this.$confirm("是否确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let temp = [];
          this.multipleSelection.map(it => {
            this.dataList = this.dataList.filter(itt => {
              return it.renderId !== itt.renderId;
            });
          });
          // this.dataList = [...temp];
        })
        .catch(() => {});
    },
    // 查询数据详情
    getDataDetail(id) {
      targetDetail(id)
        .then(r => {
          if (r.data.code == 0) {
            this.dataForm = r.data.data;
            this.dataForm.assessTarget = r.data.data.participantList.map(it => {
              return it.assessRealName;
            });
            this.dataForm.assessTarget1 = r.data.data.participantList.map(
              it => {
                return it.assessDeptName;
              }
            );
          } else {
            this.$message.error(r.data.msg);
          }
        })
        .catch(err => {});
    },
    // 查询需要自己填写的指标
    getNeedFillTarget(id) {
      //默认自己本部门
      if(this.isbr == 0){
          targetNeedFill(id)
              .then(r => {
                  if (r.data.code == 0) {
                      this.dataList = r.data.data.map((it, index) => {
                          it.renderId = index + 1;
                          return it;
                      });
                      this.oldDataList = this.dataList ;//保留一份原始指标
                  } else {
                      this.$message.error(r.data.msg);
                  }
              })
              .catch(err => {});
      }
      //能选他人部门
      if(this.isbr == 1) {
          indexExaminAllDataList(id)
              .then(r => {
                  if (r.data.code == 0) {
                      this.dataList = r.data.data.map((it, index) => {
                          it.renderId = index + 1;
                          return it;
                      });
                      this.oldDataList = this.dataList;//保留一份原始指标
                  } else {
                      this.$message.error(r.data.msg);
                  }
              })
              .catch(err => {
              });
      }

    },
    // 展示数据提供部门
    showDataProvide(data, index) {
        this.chooseDeptData = data;
        this.formulateDialog = true;
        this.jsonData = JSON.stringify([{}]);
        this.providerIndex = index;
        this.$nextTick(() => {
            this.$refs.formulateDialog.init("12", "ndts", this.jsonData, "ndcj");
        });
    },
    // 增加指标
    addZhibiao() {
      let normIds = [] ;
      let tempList = this.chooseTarget.map(it => {
        it.type = it.normLx;
        it.name = it.normName;
        it.formula = it.normGsname;
        it.formulaId = it.normGs;
        it.completeValue = '手动获取'; //it.normGetDate;
        it.itemIndex = it.normPx;
        it.keiExplain = it.normSm;
        it.unit = it.normDw;
        it.normId = it.normId ;
        normIds.push(it.normId)
        //默认自己本部门
        if(this.isbr == 0){
            it.provideDeptId = this.userData.deptId;
            it.provideDeptName = this.userData.deptName;
            it.provideRealName = this.userData.ryName;
            it.provideUserId = this.userData.userId;
            it.provideUserName = this.userData.username;
            it.isLiaison = 0
        }
        //能选他人部门
        if(this.isbr == 1){
            it.editFlag = 1;
            it.isLiaison = 0;
            it.provideUserId =it.provideUserId;
        }
        return it;
      });

        let normNameList = [] ;
        for(let i = 0; i < tempList.length; i++) {
            let tempArr1 = tempList[i]
            for(let j = 0; j < this.dataList.length; j++) {
                let tempArr2 = this.dataList[j]
                if(parseInt(tempArr2.normId) === parseInt(tempArr1.normId)){
                    normNameList.push(tempArr1.normName);
                    break;
                }
            }
        }
        if (normNameList.length>0){
            this.$message.error("“"+normNameList.toString()+"”不可重复添加") ;
        }

      const arr = [...this.dataList, ...Object.assign(tempList)]; //父子数据合并
      const newArr = arr.reduce(function (tempArr, item) { //去重
          if (tempArr.findIndex((ele) => parseInt(ele.normId) === parseInt(item.normId)) === -1) {
              tempArr.push(item)
          }
          return tempArr
      }, []);
      this.dataList = newArr ; //去重后的数据

      this.dialogVisible = false;
      this.dataList.map((it, index) => {
          it.renderId = index + 1;
      });


    },
    // 数据提供部门选择后的确定
    submitfy1(data) {
        if (this.dialogTitle == "编辑") {
            if (data.selectorgdata.length == 0) {
                this.dataList.map(it => {
                    if (it.renderIndex == this.chooseDeptData.renderIndex) {
                        this.$set(it, "provideRealName", data.tableDataUser[0].ryName);
                        this.$set(it, "provideUserName", data.tableDataUser[0].userCode);
                        this.$set(it, "provideUserId", data.tableDataUser[0].userId);
                        this.$set(it, "provideDeptName", data.tableDataUser[0].deptName);
                        this.$set(it, "provideDeptId", data.tableDataUser[0].deptId);
                        this.$set(it, "isLiaison", 0);
                    }
                });
            } else {
                this.dataList.map(it => {
                    if (it.renderIndex == this.chooseDeptData.renderIndex) {
                        this.$set(it, "provideRealName", data.selectorgdata[0].ryName);
                        this.$set(it, "provideUserName", data.selectorgdata[0].userCode);
                        this.$set(it, "provideUserId", data.selectorgdata[0].userId);
                        this.$set(it, "provideDeptName", data.selectorgdata[0].deptName);
                        this.$set(it, "provideDeptId", data.selectorgdata[0].deptId);
                        this.$set(it, "isLiaison", 1);
                    }
                });
            }
        } else {

            if (data.selectorgdata.length == 0) {
                this.dataList.map(it => {
                    if (it.normId == this.chooseDeptData.normId) {
                        this.$set(it, "provideRealName", data.tableDataUser[0].ryName);
                        this.$set(it, "provideUserName", data.tableDataUser[0].userCode);
                        this.$set(it, "provideUserId", data.tableDataUser[0].userId);
                        this.$set(it, "provideDeptName", data.tableDataUser[0].deptName);
                        this.$set(it, "provideDeptId", data.tableDataUser[0].deptId);
                        this.$set(it, "isLiaison", 0);
                    }
                });
            } else {
                this.dataList.map(it => {
                    if (it.normId == this.chooseDeptData.normId) {
                        this.$set(it, "provideRealName", data.selectorgdata[0].ryName);
                        this.$set(it, "provideUserName", data.selectorgdata[0].userCode);
                        this.$set(it, "provideUserId", data.selectorgdata[0].userId);
                        this.$set(it, "provideDeptName", data.selectorgdata[0].deptName);
                        this.$set(it, "provideDeptId", data.selectorgdata[0].deptId);
                        this.$set(it, "isLiaison", 1);
                    }
                });
            }
        }
    },
    // 指标组件传过来的数据
    getRow(rows) {
      this.chooseTarget = rows;
    },
    // 显示指标库
    showTarLibrary() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.zhibiaoRef.init(1, 1);
      });
    },
    // 指标选中
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 确定
    handleConfirm() {
      //原数据和新添加的数据对比，返回非重复值
      const res= this.dataList.filter((e)=>!this.oldDataList.some((e2)=>parseInt(e2.normId)===parseInt(e.normId)))
      let normIds = res.map(it=>{
          return it.normId ;
      })

      this.$refs.dataForm.validate(valid => {
        if (valid) {
          let submitDataList = this.dataList.map(it => {
            delete it.createDeptId;
            delete it.createDeptName;
            delete it.createTime;
            delete it.createUserId;
            delete it.createUserName;
            delete it.dataState;
            delete it.editDeptId;
            delete it.editDeptName;
            delete it.editTime;
            delete it.editUserId;
            delete it.editUserName;
            delete it.tenantId;
            delete it.id;
            it.assessId = this.fatherData.assessId;
            return it;
          });

            //验证权重
          const szValid = /^[0-9]*$/;
          let flagWeight = submitDataList.every( it=> {
              return !validatenull(it.weight)
          }) ;
          if(!flagWeight){
              this.$message.error('权重不可为空');
              return ;
          }

            //验证是否超200字
            let flagTargetValue = submitDataList.every( it=> {
                return validatenull(it.targetValue) || (!validatenull(it.targetValue) && it.targetValue.length<=200) ;
            }) ;
            if (!flagTargetValue){
                this.$message.error('目标值不可超过200字');
                return ;
            }


            let type;
            //默认自己本部门
            if(this.isbr == 0){
                type = 0;
            }
            //能选他人部门
            if(this.isbr == 1){
                type = 1;

                //验证指标列表中数据提供部门/人不可为空
                let flag = submitDataList.every( it=> {
                    return !validatenull(it.isLiaison) && ( (it.isLiaison==0 && !validatenull(it.provideRealName))||(it.isLiaison==1 && !validatenull(it.provideDeptName)))
                }) ;
                if(!flag){
                    this.$message.error('数据提供部门/人不可空');
                    return ;
                }
            }

            if (normIds.length == 0){ //不做验证
                saveFillTarget(submitDataList, this.fatherData.id, type)
                    .then(r => {
                        if (r.data.code == 0) {
                            this.$message.success("填报成功");
                            this.closeDialog();
                            this.$emit("closeDialog");
                        }
                    })
                    .catch(err => {});
            }else{
                checkitem(this.fatherData.id, normIds.toString()) //验证新增的指标是否有重复
                    .then(r => {
                        if (!r.data.msg) {
                            saveFillTarget(submitDataList, this.fatherData.id, type)
                                .then(r => {
                                    if (r.data.code == 0) {
                                        this.$message.success("填报成功");
                                        this.closeDialog();
                                        this.$emit("closeDialog");
                                    }
                                })
                                .catch(err => {});
                        }else{
                            this.$message.error(r.data.msg) ;
                        }
                    })
                    .catch(err => {});
            }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 初始化
    init(data) {

      console.log(data);
      this.visible = true;
      this.fatherData = data;

      this.isbr = data.isbr;
      this.getDataDetail(data.id);
      this.getNeedFillTarget(data.id);
      this.getNormDataTypes() ; //数据获取方式列表
    },
    // 关闭
    closeDialog() {
      this.visible = false;
      this.$emit("closeDialog");
    },
    //数据获取方式列表
    getNormDataTypes(){
        remoteDict("sys_norm_sjhqfs").then(response => {
            this.dataFromList = response.data.data;
        });
    },
  }
};
</script>

<style lang="scss">
.tabBox {
  width: 100%;
  .btnBox {
    display: flex;
    justify-content: space-between;
  }
}
</style>
